package cn.topcodes.tcsf.cms.web.controller;

import cn.topcode.unicorn.utils.CollectionUtil;
import cn.topcode.unicorn.utils.JsonUtil;
import cn.topcode.unicorn.utils.StringUtil;
import cn.topcode.unicorn.utils.ValidationUtil;
import cn.topcodes.tcsf.admin.commons.api.controller.admin.AdminController;
import cn.topcodes.tcsf.admin.commons.api.domain.ApiResponseEntity;
import cn.topcodes.tcsf.cms.domain.entity.*;
import cn.topcodes.tcsf.cms.domain.form.ProductionForm;
import cn.topcodes.tcsf.cms.domain.vo.AlbumVo;
import cn.topcodes.tcsf.cms.domain.vo.ProductionParameter;
import cn.topcodes.tcsf.cms.domain.vo.ProductionVo;
import cn.topcodes.tcsf.cms.domain.vo.StaticFilesVo;
import cn.topcodes.tcsf.cms.service.AlbumCatalogService;
import cn.topcodes.tcsf.cms.service.ConfigService;
import cn.topcodes.tcsf.cms.service.ProductionService;
import cn.topcodes.tcsf.cms.service.ProductionTagService;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 产品管理控制器
 *
 * @author Yvan
 * @date 2018-02-09 10:46:47
 */
@Controller
@RequestMapping("/admin/cms/production")
public class ProductionController extends AdminController<Production, ProductionVo, ProductionForm> {

    @Autowired
    private AlbumCatalogService albumCatalogService;

    @Autowired
    private ProductionService productionService;

    @Autowired
    private ConfigService configService;

    @Autowired
    private ProductionTagService productionTagService;

    @Override
    protected String getPageFolder() {
        return "/cms/production";
    }

    @Override
    protected void entity2VoDiff(Production entity, ProductionVo vo) {
        AlbumCatalog albumCatalog = albumCatalogService.findOne(entity.getCatalogId());
        vo.setCatalogName(albumCatalog == null ? null : albumCatalog.getName());
        String contentImg = entity.getPictures();
        List<String> imgs = new ArrayList<>();
        if (StringUtils.isNotBlank(contentImg)) {
            List<String> list = Arrays.asList(contentImg.split(","));
            for (String s : list) {
                imgs.add(OtherController.FILE_PATH + "?path=" + s);
            }
        }
        vo.setImages(imgs);
        super.entity2VoDiff(entity, vo);
    }

    @Override
    public ApiResponseEntity create(HttpServletRequest request, @Valid @ApiParam("创建资源表单") ProductionForm form, BindingResult result) {
        ValidationUtil.validate(result);
        Production entity = this.form2Entity(form);
        if (entity.getIsShow() == null) {
            entity.setIsShow(false);
        }
        if (entity.getIsTop() == null) {
            entity.setIsTop(false);
        }
        Long id = this.productionService.create(entity);
        return ApiResponseEntity.buildOK().setBody(id);
    }

    @Override
    public String update(Long id, HttpServletRequest request, Model model) {

        Production production = productionService.findOne(id);
        ProductionVo productionVo = new ProductionVo();
        Long catalogId = production.getCatalogId();
        AlbumCatalog albumCatalog = albumCatalogService.findOne(catalogId);

        productionVo.setId(production.getId());
        productionVo.setCatalogId(production.getCatalogId());
        productionVo.setDescription(production.getDescription());
        productionVo.setName(production.getName());
        productionVo.setCatalogName(albumCatalog.getName());
        productionVo.setIsShow(production.getIsShow() == null ? false : production.getIsShow());
        productionVo.setIsTop(production.getIsTop() == null ? false : production.getIsTop());

        String contentImg = production.getPictures();
        productionVo.setContentImg(contentImg);
        List<StaticFilesVo> staticFilesVos = new ArrayList<>();
        if (StringUtil.isNotBlank(contentImg)) {
            String[] imgs = contentImg.split(",");
            for (String img : imgs) {
                File file = new File(configService.getFileFolderPath() + img);
                if (file.exists()) {
                    StaticFilesVo staticFilesVo = new StaticFilesVo();
                    staticFilesVo.setOrigSize(file.length());
                    staticFilesVo.setSize(file.length());
                    staticFilesVo.setLastModifiedDate(new Date(file.lastModified()));
                    staticFilesVo.setType("image/jpeg");
                    staticFilesVo.setId(file.getName());
                    staticFilesVo.setName(file.getName());
                    staticFilesVo.setPreviewImage(OtherController.FILE_PATH + "?path=" + img);
                    staticFilesVos.add(staticFilesVo);
                }
            }
        }
        List<ProductionTag> labelServiceAll = productionTagService.findAll();
        if (null != labelServiceAll) {
            String keyword = production.getKeyword();
            if (StringUtils.isNotBlank(keyword)) {
                List<String> strings = Arrays.asList(keyword.split(","));
                productionVo.setKeywords(strings);
            }
            productionVo.setLabels(labelServiceAll.stream().map(e -> e.getName()).collect(Collectors.toList()));
        }
        model.addAttribute("entity", productionVo);
        model.addAttribute("staticFile", JsonUtil.toJson(staticFilesVos));
        return this.getPageFolder() + "/update";
    }

    @RequestMapping(value = "updateContentImg")
    @ResponseBody
    public ApiResponseEntity updateContentImg(@RequestParam(value = "id") Long id,
                                              @RequestParam(value = "content") String content,
                                              HttpServletResponse response) throws IOException {
        Production production = this.productionService.findOneOrFail(id);
        String pictures = production.getPictures();
        List<String> strings = Arrays.asList(pictures.split(","));
        List<String> collect = strings.stream()
                .filter(e -> !e.contains(content))
                .collect(Collectors.toList());
        return ApiResponseEntity.buildOK().setBody(CollectionUtil.array2String(collect));
    }

    @Override
    public ApiResponseEntity<Void> update(HttpServletRequest request, @Valid @ApiParam("更新资源表单") ProductionForm form, BindingResult result) {
        ValidationUtil.validate(result);
        Production t = this.form2Entity(form);
        t.setIsShow(form.getIsShow() == null ? false : true);
        t.setIsTop(form.getIsTop() == null ? false : true);
        this.productionService.update(t);
        return ApiResponseEntity.buildOK();
    }

    @RequestMapping(value = "parameter", method = RequestMethod.GET)
    public String parameterIndex(@RequestParam(value = "id", required = true) Long id,
                                 Model model) {
        Production production = productionService.findOne(id);
        String params = production.getParams();
        ProductionParameter pp = new ProductionParameter();
        pp.setId(production.getId());
        if (StringUtils.isNotBlank(params)) {
            String[] split = params.split(",", -1);
            if (split.length >= 9) {
                pp.setNo(split[0]);
                pp.setPrice(StringUtils.isBlank(split[1]) ? 0F : Float.parseFloat(split[1]));
                pp.setSales(StringUtils.isBlank(split[2]) ? 0L : Long.parseLong(split[2]));
                pp.setType(split[3]);
                pp.setSpecifications(split[4]);
                pp.setMaterial(split[5]);
                pp.setColor(split[6]);
                pp.setBrand(split[7]);
                pp.setModel(split[8]);
                pp.setInventory(StringUtils.isBlank(split[9]) ? 0L : Long.parseLong(split[9]));
            }
        }
        model.addAttribute("entity", pp);
        return this.getPageFolder() + "/parameter";
    }

    @RequestMapping(value = "updateProductionParams")
    @ResponseBody
    public ApiResponseEntity updateProductionParams(@Valid ProductionParameter productionParameter) {

        Long parameterId = productionParameter.getId();
        List<String> params = new ArrayList<>();
        params.add(productionParameter.getNo() == null ? "" : productionParameter.getNo());
        params.add(productionParameter.getPrice() == null ? "" : productionParameter.getPrice() + "");
        params.add(productionParameter.getSales() == null ? "" : productionParameter.getSales() + "");
        params.add(productionParameter.getType() == null ? "" : productionParameter.getType());
        params.add(productionParameter.getSpecifications() == null ? "" : productionParameter.getSpecifications());
        params.add(productionParameter.getMaterial() == null ? "" : productionParameter.getMaterial());
        params.add(productionParameter.getColor() == null ? "" : productionParameter.getColor());
        params.add(productionParameter.getBrand() == null ? "" : productionParameter.getBrand());
        params.add(productionParameter.getModel() == null ? "" : productionParameter.getModel());
        params.add(productionParameter.getInventory() == null ? "" : productionParameter.getInventory() + "");
        Production production = productionService.findOne(parameterId);
        production.setParams(CollectionUtil.array2String(params));
        productionService.update(production);
        return ApiResponseEntity.buildOK();
    }

    @Override
    public String create(HttpServletRequest request, Model model) {

        List<ProductionTag> all = productionTagService.findAll();
        model.addAttribute("labels", all);
        return this.getPageFolder() + "/create";
    }


}
